const jwt = require('jsonwebtoken')

const sign = (option) => {
    return jwt.sign(option, '666', {
        expiresIn: 86400
    }) // 加盐
}

const verify = () => {
    return async (ctx, next) => {
        const jwtToken = ctx.req.headers.authorization
        // console.log(jwtToken);
        if (jwtToken) {
            try {
                const decoded = jwt.verify(jwtToken, '666')
                if (decoded.id) { // 合法
                    ctx.userId = decoded.id
                    ctx.nickname = decoded.nickname
                    await next()
                }
            } catch (error) {
                ctx.body = {
                    code: "809",
                    message: '登录过期，请重新登录',
                    data: error
                }
            }
        } else {
            ctx.body = {
                code: "808",
                message: '请登录',
            }
        }
    }
}

module.exports = {
    sign,
    verify
}